<?php

namespace XWAM\Controller;

/**
 * OAuthController 类
 *
 * @since VER:1.0; DATE:2016-4-21; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
 */
class OAuthController extends \Think\Controller {

    // 2016-4-21 SoChishun Added.
    function transfer($site_id, $user_name) {
        if (!$site_id || !$user_name) {
            $this->error('参数有误!');
        }
        // 创建新的数据库
        if (\XWAM\Model\InstallModel::check_db_exists($site_id)) {
            // 安装用户数据
            \XWAM\Model\InstallModel::ensure_site($site_id, $user_name);
            // 首次同步坐席数据
            $user=new \XWAM\Model\UserSeatModel();
            $user->user_from_xcall($site_id);
        } else {
            // 安装数据表
            \XWAM\Model\InstallModel::ensure_database($site_id, $user_name);
        }
        // 1.用户在xcall登录，读取db_xcall.t_porg_site中的siteID，保存信息到session[site_conf](db_name,site_id)，快捷登录到xcrm
        // 2.在xcrm中，C('DB_NAME',session('site_conf','db_name'));
        $m_siteconf = new \XWAM\Model\SiteConfModel();
        $data = $m_siteconf->find_site($site_id, $user_name);
        session('site_conf', $data);
        redirect(U('login', 'user_name=' . urlencode($user_name) . '&site_id=' . $site_id));
    }

    // 2016-4-21
    public function login($user_name = '', $site_id = '') {
        if (!$user_name || !$site_id) {
            exit('参数有误!');
        }
        $data = D('SiteConf')->find_site($site_id, $user_name, false);
        if (!$data) {
            exit('未开通CRM功能!');
        }
        session('site_conf', $data);
        $m_login = new \XWAM\Model\LoginModel();
        $result = $m_login->login($user_name, 'soc:', null, $msg);
        if ($result) {
            session('login', $msg);
            redirect(U('Index/index'));
        } else {
            exit($msg);
        }
    }

    // 2016-4-22
    public function logout() {
        $m_login = new \XWAM\Model\LoginModel();
        $m_login->logout();
        redirect('/xcall/index.php/XCall/Login/index.html');
    }

}
